# -*- coding:utf-8 -*-
"""
Author：Administrator
Date:2021年08月24日
"""
import os
import comtypes.client


def get_path():
	# 指定路径
	# 只需要修改相应路径就可以了
	path = r'E:\07PythonWorks\python_docx\01python自动化_docx孙中华\练习'
	# 获取所有文件名的列表
	filename_list = os.listdir(path)
	# 获取所有word文件名列表
	wordname_list = [filename for filename in filename_list \
	                 if filename.endswith((".doc", ".docx"))]
	for wordname in wordname_list:
		# 分离word文件名称和后缀，转化为pdf名称
		pdfname = os.path.splitext(wordname)[0] + '.pdf'
		# 如果当前word文件对应的pdf文件存在，则不转化
		if pdfname in filename_list:
			continue
		# 拼接 路径和文件名
		wordpath = os.path.join(path, wordname)
		pdfpath = os.path.join(path, pdfname)
		# 生成器
		yield wordpath, pdfpath


def convert_word_to_pdf():
	word = comtypes.client.CreateObject("Word.Application")
	word.Visible = 0
	for wordpath, pdfpath in get_path():
		newpdf = word.Documents.Open(wordpath)
		newpdf.SaveAs(pdfpath, FileFormat=17)
		newpdf.Close()


if __name__ == "__main__":
	convert_word_to_pdf()
